package com.situ.web.dao.impl;

import com.situ.web.dao.IBanjiDao;
import com.situ.web.pojo.Banji;
import com.situ.web.pojo.vo.BanjiCountVO;
import com.situ.web.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BanjiDaoImpl implements IBanjiDao {
    @Override
    public List<BanjiCountVO> selectBanjiCount() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<BanjiCountVO> list = new ArrayList<>();
        try {
            connection = JDBCUtil.getConnection();
            String sql = "SELECT b.name,COUNT(*) AS 'value'\n" +
                    "FROM student AS s INNER JOIN banji AS b\n" +
                    "ON s.banji_id=b.id\n" +
                    "GROUP BY b.id";
            statement = connection.prepareStatement(sql);
            System.out.println(statement);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                String name = resultSet.getString("name");
                int value = resultSet.getInt("value");
                BanjiCountVO banjiCountVO = new BanjiCountVO(name, value);
                list.add(banjiCountVO);
            }
        }  catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {//不管抛不抛出异常都会执行的代码
            JDBCUtil.close(connection, statement, resultSet);
        }
        return  list;
    }

    @Override
    public List<Banji> selectAll() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Banji> list = new ArrayList<>();
        try {
            connection = JDBCUtil.getConnection();
            String sql = "select id,name from banji";
            statement = connection.prepareStatement(sql);
            System.out.println(statement);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                Banji banji = new Banji(id, name);
                list.add(banji);
            }
        }  catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {//不管抛不抛出异常都会执行的代码
            JDBCUtil.close(connection, statement, resultSet);
        }
        return  list;
    }
}
